package abel.wlmr.model.unit;

import org.joda.time.DateTime;

import abel.wlmr.model.WlmrBaseUnit;
import abel.wlmr.model.WlmrException;
import abel.wlmr.model.type.C1DateTimeType;
import io.netty.buffer.ByteBuf;

/**
 * B.5.5.1.3.3 F31： 对时命令
 * 数据单元格式见表 B.51。
 * 表B.51 对时命令数据单元格式
 * 数据内容 数据格式 字节数
 * 秒、分、时、日、星期-月、年 见附录 C.1 6
 * 
 * @author Abel
 *
 */
public class Afn05F31Unit extends WlmrBaseUnit {

    private static final short FIXED_LENGTH = 6;

    private C1DateTimeType stdTime;

    public Afn05F31Unit() {
        super();
    }

    public Afn05F31Unit(short guessedLen) {
        super(guessedLen);
    }

    /* (non-Javadoc)
     * @see abel.wlmr.model.AppUnitPart#appendBuf(io.netty.buffer.ByteBuf)
     */
    @Override
    public ByteBuf appendBuf(ByteBuf buf) {
        if (stdTime == null || stdTime.getDtValue() == null) {
            throw new IllegalArgumentException("standard time should be of 6 ascii long.");
        }

        stdTime.appendBuf(buf);

        return buf;
    }

    /* (non-Javadoc)
     * @see abel.wlmr.model.AppUnitPart#parseBuf(io.netty.buffer.ByteBuf)
     */
    @Override
    public int parseBuf(ByteBuf buf) throws WlmrException {
        if (checkBuffer(buf) < 0) {
            return -1;
        }

        stdTime = new C1DateTimeType((short) 6);
        stdTime.parseBuf(buf);

        return getGuessedLength();
    }

    /* (non-Javadoc)
     * @see abel.wlmr.model.WlmrDataPart#getMinLength()
     */
    @Override
    public int getMinLength() {
        return FIXED_LENGTH;
    }

    /* (non-Javadoc)
     * @see abel.wlmr.model.WlmrDataPart#getFinalLen()
     */
    @Override
    public short getFinalLen() {
        return FIXED_LENGTH;
    }

    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return String.format("{stdTime:%s}", stdTime);
    }

    public DateTime getMeterC20Joda() {
        return stdTime.getDtValue();
    }

    /**
     * @return the stdTime
     */
    public C1DateTimeType getStdTime() {
        return stdTime;
    }

    /**
     * @param stdTime
     *            the stdTime to set
     */
    public void setStdTime(C1DateTimeType stdTime) {
        if (stdTime == null || stdTime.getDtValue() == null) {
            throw new IllegalArgumentException("std time can't be null");
        }

        this.stdTime = stdTime;
    }

}
